﻿using System;
using System.Linq;
using Telerik.Web.UI;
using Thuoc24h.BasePage;
using Thuoc24h.Business;
using Thuoc24h.Common;
using Thuoc24h.Common.Enums;
using Thuoc24h.Data;

namespace Thuoc24h.AdminCP.Pages
{
    public partial class ProductEdit : BasePages
    {
        private int _id;
        private Product _obj = new Product();
        private const int CategoryTypeId = 1;
        protected void Page_Load(object sender, EventArgs e)
        {

            _id = Convert.ToInt32(Request.QueryString["ID"]);

            if (!Page.IsPostBack)
            {
                lnNoti.Text = "Thêm sản phẩm trước...";
                radCreateDate.SelectedDate = DateTime.Now;
                FillDataListBoxRoot();
                BindProductImages();
                BindProductPrice();
                if (_id > 0)
                {
                    lnNoti.Visible = false;
                    pnlAddProductImage.Visible = true;
                    btnSave.Text = ActionNames.Update;
                    BindData();
                }
                else
                {
                    pnlAddProductImage.Visible = false;
                    lnNoti.Visible = true;
                    btnSave.Text = ActionNames.AddNew;
                }

                UnitCbb.DataSource = Enum.GetValues(typeof(Unit)).Cast<Unit>().Select(item => new
                {
                    Text = item.ToString(),
                    Value = ((byte)item).ToString()
                });
                UnitCbb.DataTextField = "Text";
                UnitCbb.DataValueField = "Value";
                UnitCbb.DataBind();

                UnitDefaultCbb.DataSource = Enum.GetValues(typeof(Unit)).Cast<Unit>().Select(item => new
                {
                    Text = item.ToString(),
                    Value = ((byte)item).ToString()
                });
                UnitDefaultCbb.DataTextField = "Text";
                UnitDefaultCbb.DataValueField = "Value";
                UnitDefaultCbb.DataBind();
               
            }
          

        }


        public void FillDataListBoxRoot()
        {
            radTreeCategories.DataSource = ReviewRepository.GetCategoryParent(CategoryTypeId);
            radTreeCategories.DataValueField = "Id";
            radTreeCategories.DataTextField = "Name";
            radTreeCategories.DataFieldParentID = "ParentId";
            radTreeCategories.DataFieldID = "Id";
            radTreeCategories.DataBind();

        }



        private void GetData()
        {
            _obj.Name = txtName.Text;
            _obj.UnsignName = txtUnsignName.Text;
            _obj.CategoryId = radTreeCategories.SelectedValue.ToInt32Return0();
            _obj.Description = edtDescription.Text;
            _obj.Detail = edtDetail.Content;
            //_obj.Price = txtPrice.Text.ToDoubleReturn0();
            //_obj.DiscountPercent = txtDiscountPercent.Text.ToDoubleReturn0();
            _obj.IsGroupBuy = cbIsGroupBuy.Checked == true;
            _obj.IsSalesOff = IsSalesOff.Checked == true;
            _obj.CreatedDate = radCreateDate.SelectedDate;
            _obj.ThumbImage = txtFileName.Text;
            _obj.DiscountDescription = txtDesDiscount.Text;
            _obj.Unit = UnitDefaultCbb.SelectedValue.ToInt32Return0();
        }
        private void Reset()
        {

            txtName.Text = string.Empty;
            txtDesDiscount.Text = txtUnsignName.Text = string.Empty;
            radTreeCategories.Nodes.Clear();
            edtDescription.Text = string.Empty;
            edtDetail.Content = string.Empty;
            //txtPrice.Text.ToDoubleReturn0();
           // txtDiscountPercent.Text.ToDoubleReturn0();
            IsSalesOff.Checked = cbIsGroupBuy.Checked == false;
            radCreateDate.SelectedDate = DateTime.Now;
            txtFileName.Text = string.Empty;

        }


        private void SaveData()
        {
            if (_id > 0)
            {
                _obj = context.Products.SingleOrDefault(item => item.Id == _id);
                if (_obj != null)
                {
                    GetData();
                }

            }
            else
            {
                GetData();
                _obj.BuyCount = _obj.ViewCount = 0;
                context.Products.AddObject(_obj);
            }

            if (context.SaveChanges() > 0)
            {
                if (_obj != null) Utils.Redirect(UrlManager.Admin.ProductEdit, _obj.Id.ToString());
            }
        }
        private void BindData()
        {

            _obj = ReviewRepository.GetProductById(_id);
            txtName.Text = _obj.Name;
            txtUnsignName.Text = _obj.UnsignName;
            edtDescription.Text = _obj.Description;
            edtDetail.Content = _obj.Detail;
            IsSalesOff.Checked = _obj.IsSalesOff ?? false;
            cbIsGroupBuy.Checked = _obj.IsGroupBuy ?? false;
            radCreateDate.SelectedDate = _obj.CreatedDate;
            txtFileName.Text = _obj.ThumbImage;
            //txtPrice.Text = _obj.Price.ToString();
            //UnitCbb.SelectedValue = _obj.Unit.ToString();
            //txtDiscountPercent.Text = _obj.DiscountPercent.ToString();
            //txtPriceOff.Text = String.Format("{0:0,0}", ((_obj.Price / 100) * (100 - _obj.DiscountPercent)));
            txtDesDiscount.Text = _obj.DiscountDescription;
            UnitDefaultCbb.SelectedValue = _obj.Unit.ToString();
            if (_obj.CategoryId != null)
            {
                var categoryId = _obj.CategoryId.Value;
                var node = radTreeCategories.FindNodeByValue(categoryId.ToString());
                node.Selected = true;

            }
        }

        protected void btnSave_OnClick(object sender, EventArgs e)
        {
            SaveData();
        }

        protected void OnClick(object sender, EventArgs e)
        {
            Reset();
        }


        private void BindProductImages()
        {
            gridData.DataSource = ReviewRepository.GetProductImages(_id);
            gridData.DataBind();
        }
        private void BindProductPrice()
        {
            gridDataPrice.DataSource = ReviewRepository.GetProductPriceUnit(_id);
            gridDataPrice.DataBind();
        }

        protected void gridData_ItemCommand(object sender, GridCommandEventArgs e)
        {
            string id = string.Empty;

            var commandName = e.CommandName;
            var gridDataItem = e.Item as GridDataItem;
            if (gridDataItem != null)
            {
                id = gridDataItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Id"].ToString();
            }

            switch (commandName)
            {
                case CommandNames.Delete:
                    ReviewRepository.ProductImageDelete(id.ToInt32Return0());
                    BindProductImages();
                    break;

            }
        }
        protected void gridDataPrice_ItemCommand(object sender, GridCommandEventArgs e)
        {
            string id = string.Empty;

            var commandName = e.CommandName;
            var gridDataItem = e.Item as GridDataItem;
            if (gridDataItem != null)
            {
                id = gridDataItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Id"].ToString();
            }
            switch (commandName)
            {
                case CommandNames.Delete:
                    ReviewRepository.ProductUnitDelete(id.ToInt32Return0());
                    BindProductPrice();
                    break;

            }
        }
  
        protected void btnImageSave_OnClick(object sender, EventArgs e)
        {
            var productImage = new ProductImage();
            productImage.ProductId = _id;
            productImage.ImageUrl = txtProductImage.Text;
            context.ProductImages.AddObject(productImage);
            if (context.SaveChanges() > 0)
            {
                txtProductImage.Text = string.Empty;
                BindProductImages();
            }



        }

        protected void btFinish_OnClick(object sender, EventArgs e)
        {
            Response.Redirect(UrlManager.Admin.ProductView);
        }

        protected void btnPriceSave_OnClick(object sender, EventArgs e)
        {
            var priceUnit = new PriceUnit();
            priceUnit.ProductId = _id;
            priceUnit.Unit = UnitCbb.SelectedValue.ToInt32Return0();
            priceUnit.Price = txtPriceUnit.Text.ToDoubleReturn0();
            priceUnit.DiscountPercent = txtPriceUnitDiscountPercent.Text.ToDoubleReturn0();
            context.PriceUnits.AddObject(priceUnit);
            if (context.SaveChanges() > 0)
            {
                txtPriceUnit.Text = txtPriceUnitDiscountPercent.Text = string.Empty;
                BindProductPrice();
            }

           
        }

      
    }
}